// g++ sfml-sound.cc `pkg-config --cflags --libs sfml-all` -std=c++20

#include <SFML/Audio.hpp>

#include <iostream>
#include <string>

#define USE_RESOURCE "killdeer.wav" // CONF: fix this USE_RESOURCE for your path

/// @desc: play a sound when you define your own resource file
void playSound()
{
    // Load a sound buffer from a wav file
    sf::SoundBuffer sound_buffer;
    if (!sound_buffer.loadFromFile(USE_RESOURCE)) return;

    // Display sound informations
    std::cout << USE_RESOURCE":" << std::endl;
    std::cout << " " << sound_buffer.getDuration().asSeconds() << " seconds" << std::endl;
    std::cout << " " << sound_buffer.getSampleRate() << " sample / sec" << std::endl;
    std::cout << " " << sound_buffer.getChannelCount() << " channels" << std::endl;

    // Create a sound instance and play it
    sf::Sound sound_inst(sound_buffer);
    sound_inst.play();

    // Loop while the sound is playing
    while (sound_inst.getStatus() == sf::Sound::Playing)
    {
        // Leave some CPU time for other processes
        sf::sleep(sf::milliseconds(100));

        // Display the playing position
        std::cout << "\rPlaying... " << sound_inst.getPlayingOffset().asSeconds() << " sec\t";
        std::cout << std::flush;
    }

    std::cout << std::endl << std::endl; // Why double endl?
}

/// @desc: play a sound when you provide a filename
void playMusic(const char* filename)
{
    // Load a music file: what is the definition of a music file ?
    sf::Music music_inst;
    if (!music_inst.openFromFile(filename)) return;

    std::cout << filename << ": " << std::endl;
    std::cout << " " << music_inst.getDuration().asSeconds() << " seconds" << std::endl;
    std::cout << " " << music_inst.getSampleRate() << " sample / sec" << std::endl;
    std::cout << " " << music_inst.getChannelCount() << " channels" << std::endl;

    music_inst.play();

    // Loop while the music is playing
    while (music_inst.getStatus() == sf::Music::Playing)
    {
        // Leave some CPU time for other process
        sf::sleep(sf::milliseconds(100));

        // Display the playing position
        std::cout << "\rPlaying..." << music_inst.getPlayingOffset().asSeconds() << " sec\t";
        std::cout << std::flush;
    }

    std::cout << std::endl << std::endl;
}

int main()
{

//    playSound();

//    playMusic("a.ogg"); // support ogg file format

//    playMusic("b.flac"); // support flac file format

    playMusic("c.mp3"); // support mp3 file format

    // Wait until user press 'ENTER' key
    std::cout << "Press enter to exit..." << std::endl;
    std::cin.ignore(10000, '\n');

    return 0;
}
// END
